package controller

import (
	"encoding/json"
	"net/http"
	config "todolist-go/src/Config"
	service "todolist-go/src/Service"
	utils "todolist-go/src/Utils"
	vo "todolist-go/src/Vo"
)

//注册接口
func Register(w http.ResponseWriter, r *http.Request) {
	// 根据请求body创建一个json解析器实例
	//该方法是用于处理POST请求
	decoder := json.NewDecoder(r.Body)

	// 用于存放参数key=value数据
	//var params map[string]string
	var registerParam vo.RegisterParams
	decoder.Decode(&registerParam)
	res, err := service.UserRegister(&registerParam)
	if err != nil {
		return
	}
	//告诉浏览器要返回json数据
	w.Header().Set("content-type", "text/json")
	msg, _ := json.Marshal(res)
	w.Write(msg)
}

//登录接口
func Login(w http.ResponseWriter, r *http.Request) {
	decoder := json.NewDecoder(r.Body)
	var loginParams vo.LoginParams
	decoder.Decode(&loginParams)
	res := service.UserLogin(&loginParams)
	w.Header().Set("content-type", "text/json")
	msg, _ := json.Marshal(res)
	w.Write(msg)
}

//获取当前登陆用户信息接口
func CurrentUser(w http.ResponseWriter, r *http.Request) {
	//1.获得请求头中的token
	token := r.Header.Get(config.JwtHeader)
	res := service.GetCurrentUser(&token)
	if (res == utils.Result{}) {
		res = utils.NewResult().DefaultFail("redis读取失败")
	}
	msg, _ := json.Marshal(res)
	w.Header().Set("content-type", "text/json")
	w.Write(msg)
}

//登出接口
func Logout(w http.ResponseWriter, r *http.Request) {
	token := r.Header.Get(config.JwtHeader)
	res := service.Logout(&token)
	msg, _ := json.Marshal(res)
	w.Write(msg)
}
